package com.yang.controller.wx;


import com.yang.bean.MarketUser;
import com.yang.bean.common.BaseRespVo;
import com.yang.bean.yvo.wx.LoginInfo;
import com.yang.bean.yvo.wx.UserInfoBean;
import com.yang.config.AliyunCompoent;
import com.yang.config.realm.MarketToken;
import com.yang.service.wx.WXAUthService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 杨庆 微信的登录
 * @since: 2022.9.9 14:07
 * @description:
 */

@RestController
@RequestMapping("wx/auth/")
public class WXAuthController {

    @Autowired
    AliyunCompoent aliyunCompoent;
    @Autowired
    WXAUthService wxaUthService;

    @RequestMapping("login")
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        Subject subject = SecurityUtils.getSubject();
        MarketToken usernamePasswordToken = new MarketToken(username, password, "wx");
        try {
            subject.login(usernamePasswordToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean authenticated = subject.isAuthenticated();
        if (!authenticated) {
            return BaseRespVo.invalidParameter("用户名密码错误");
        }
        Session session = subject.getSession();
        String sessionId = (String) session.getId();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        LoginInfo loginUserData = new LoginInfo();
        UserInfoBean userInfoBean = new UserInfoBean();
        userInfoBean.setAvatarUrl(marketUser.getAvatar());
        userInfoBean.setNickName(marketUser.getNickname());
        loginUserData.setUserInfo(userInfoBean);
        loginUserData.setToken(sessionId);
        //TODO 把对象存进去
        session.setAttribute(sessionId,marketUser);
        return BaseRespVo.ok(loginUserData);
    }


    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    /**
     * @description: 用户注册
     * []
     * @return: com.yang.bean.common.BaseRespVo
     * @author: 杨庆
     * @time: 2022.9.10 10:39
     */
    @RequestMapping("regCaptcha")
    public BaseRespVo regCaptcha(@RequestBody Map map) {
        String mobile = (String) map.get("mobile");
        try {
            aliyunCompoent.sendMessages(mobile);
        } catch (Exception e) {

            return BaseRespVo.error("验证码发送失败");
        }
        return BaseRespVo.ok();
    }


    @RequestMapping("register")
    public BaseRespVo register(@RequestBody @Valid MarketUser marketUser, BindingResult bindingResult) {
        //TODO 参数结果的校验
        if (bindingResult.hasFieldErrors()) {//是否有校验错误
            FieldError fieldError = bindingResult.getFieldError();//拿到校验错误
            // 拿到成员变量名 → 请求参数名
            String field = fieldError.getField();
            // 拿到错误的值
            Object rejectedValue = fieldError.getRejectedValue();
            // 消息
            String defaultMessage = fieldError.getDefaultMessage();
            StringBuffer sb = new StringBuffer();
            String msg = sb.append("请求参数")
                    .append(field)
                    .append("传入的值")
                    .append(rejectedValue)
                    .append("有问题 -- > ")
                    .append(defaultMessage).toString();
            return BaseRespVo.invalidParameter(msg);
        }

        BaseRespVo baseRespVo = wxaUthService.registerUser(marketUser);
        //注册成功登录
        String username = marketUser.getUsername();
        String password = marketUser.getPassword();
        HashMap<String, String> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        BaseRespVo login = login(map);
        return  login;
    }


    /**
    * @description: 用户密码的修改，根据手机号修改，说明手机号只能注册一个用户
    [marketUser]
    * @return: com.yang.bean.common.BaseRespVo
    * @author: 杨庆
    * @time: 2022.9.11 15:34
     */
    @RequestMapping("reset")
    public BaseRespVo reset(@RequestBody MarketUser marketUser){

        BaseRespVo baseRespVo = wxaUthService.resetPassword(marketUser);

        return baseRespVo;

    }



}
